<template>
  <!--定时广播-->
  <el-dialog
    title="定时广播"
    custom-class="timeBroadcast-dialog"
    :close-on-click-modal="false"
    :modal="false"
    :visible.sync="timeBroadcastDialog"
    :before-close="handleClose"
    width="70%"
  >
    <el-tabs v-model="currentTab" type="card" @tab-click="handleClick">
      <el-tab-pane label="单次广播" name="once"></el-tab-pane>
      <el-tab-pane label="周期广播" name="looping"></el-tab-pane>
    </el-tabs>

    <el-table
      :data="tableData"
      ref="myTable"
      height="500"
      style="width: 100%"
      :highlight-current-row="true"
      cell-class-name="table-cell-custom"
      header-cell-class-name="table-herder-custom"
      size="small"
    >
      <el-table-column key="1" width="55" type="selection" align="center"></el-table-column>
      <el-table-column
        key="2"
        prop="beginDate"
        show-overflow-tooltip
        v-if="currentTab == 'once'"
        label="开始日期"
        align="center"
      ></el-table-column>
      <el-table-column
        key="3"
        prop="endDate"
        show-overflow-tooltip
        v-if="currentTab == 'once'"
        label="截止日期"
        align="center"
      ></el-table-column>
      <el-table-column
        key="4"
        prop="time"
        show-overflow-tooltip
        v-if="currentTab == 'once'"
        label="开始时间"
        align="center"
      >
        <template slot-scope="scope">
          <span>
            {{ scope.row.time.substr(0, 2) }}:
            {{ scope.row.time.substr(2, 2) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        key="5"
        prop="playDay"
        show-overflow-tooltip
        v-if="currentTab == 'looping'"
        label="播放日期"
        align="center"
      ></el-table-column>
      <el-table-column
        key="6"
        prop="time"
        show-overflow-tooltip
        v-if="currentTab == 'looping'"
        label="播放时间"
        align="center"
      >
        <template slot-scope="scope">
          <span>
            {{ scope.row.time.substr(0, 2) }}:
            {{ scope.row.time.substr(2, 2) }}
          </span>
        </template>
      </el-table-column>

      <el-table-column prop="createTime" show-overflow-tooltip label="创建时间" align="center">
        <template slot-scope="scope">
          <span>
            {{ scope.row.createTime.substr(0, 4) }}/
            {{ scope.row.createTime.substr(4, 2) }}/
            {{ scope.row.createTime.substr(6, 2) }}
            {{ scope.row.createTime.substr(8, 2) }}:
            {{ scope.row.createTime.substr(10, 2) }}:
            {{ scope.row.createTime.substr(12, 2) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="fileName" show-overflow-tooltip label="广播文件" align="center"></el-table-column>
      <el-table-column prop="dutyName" show-overflow-tooltip label="播放次数" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.callLoop == -1">循环</span>
          <span v-if="scope.row.callLoop != -1">{{scope.row.callLoop}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="state" show-overflow-tooltip label="广播状态" align="center">
        <template slot-scope="scope">
          <span>{{callStatus[scope.row.state].text}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="dutyName" show-overflow-tooltip label="广播成员" align="center">
        <template slot-scope="scope">
          <el-link @click="handleGetMemberList(scope.row)">查看广播成员</el-link>
        </template>
      </el-table-column>
    </el-table>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleAdd" size="small">创建广播</el-button>
      <el-button @click="handleDel" size="small">删除广播</el-button>
      <!-- <el-button @click="handleDel" size="small">取 消</el-button> -->
    </div>
    <!-- 新增界面 -->
    <el-dialog
      title="添加广播"
      custom-class="inner-dialog"
      :close-on-click-modal="false"
      :modal="false"
      :visible.sync="dialogAdd"
      :before-close="handleAddClose"
      width="100%"
    >
      <svg-icon class="back-to-list" icon-class="back" @click="dialogAdd = false"></svg-icon>
      <div style="display:flex">
        <div style="height:500px;width:700px">
          <el-scrollbar wrap-style="overflow-x:hidden;" style="height:100%">
            <el-form ref="form" :model="form" label-width="120px" hide-required-asterisk>
              <el-form-item
                label="广播成员："
                prop="callTelNameArr"
                :rules="[
                            { required: true, 
                            message: '联动成员不能为空', trigger: 'change'},
                          ]"
              >
                <el-select
                  v-model="form.callTelNameArr"
                  multiple
                  filterable
                  allow-create
                  default-once-option
                  placeholder="请选择成员"
                  style="width: 60%;"
                  clearable
                  @clear="clearAll"
                  @remove-tag="removeUserTag"
                ></el-select>
              </el-form-item>
              <el-form-item label="选择星期：" prop="checkedCities" v-if="callMode == 'looping'">
                <el-checkbox-group v-model="checkedCities">
                  <el-checkbox v-for="city in cities" :label="city" :key="city">{{city}}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <div v-if="callMode == 'once'">
                <el-form-item
                  label="开始日期："
                  prop="beginDate"
                  :rules="[{ required: true, message: '开始日期不能为空', trigger: 'blur'},]"
                >
                  <el-date-picker
                    v-model="form.beginDate"
                    style="width:60%"
                    type="date"
                    placeholder="选择日期"
                    value-format="yyyyMMdd"
                  ></el-date-picker>
                </el-form-item>
              </div>
              <el-form-item
                label="结束日期："
                prop="endDate"
                v-if="callMode == 'once'"
                :rules="[
                            { required: true, 
                            message: '结束日期不能为空', trigger: 'blur'},
                          ]"
              >
                <el-date-picker
                  v-model="form.endDate"
                  style="width:60%"
                  type="date"
                  value-format="yyyyMMdd"
                  placeholder="选择日期"
                ></el-date-picker>
              </el-form-item>
              <el-form-item
                label="开始时间："
                prop="time"
                :rules="[
                            { required: true, message: '开始时间不能为空', trigger: 'blur'},
                          ]"
              >
                <el-time-picker v-model="form.time" value-format="HHmmss" style="width:60%"></el-time-picker>
              </el-form-item>
              <el-form-item label="播放次数：">
                <el-radio v-model="form.play" label="0" @change="radioChange">循环</el-radio>
                <br />
                <el-radio v-model="form.play" label="1" @change="radioChange">次数</el-radio>
                <el-input-number
                  v-show="showInputNum"
                  v-model="broadcastNum"
                  :min="1"
                  :max="99"
                  label="描述文字"
                ></el-input-number>
              </el-form-item>
              <el-form-item
                label="广播文件："
                prop="broadcastFile"
                :rules="[
                            { required: true, 
                            message: '请选择广播文件', trigger: 'change'},
                          ]"
              >
                <el-select
                  v-model="form.broadcastFile"
                  placeholder="请选择"
                  style="width: 60%;margin-left:5px"
                  popper-class="default-select-popper"
                >
                  <el-option
                    v-for="item in fileList"
                    :key="item.fileid"
                    :label="item.orifilename"
                    :value="item.fileid"
                  >
                    <span style="float: left">{{ item.orifilename }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </el-scrollbar>
        </div>
        <div style="height:500px;width:50%">
          <el-scrollbar class="default-scrollbar" wrap-class="default-scrollbar__wrap">
            <el-tree
              :data="userTreeData"
              icon-class="el-icon-arrow-right"
              node-key="id"
              highlight-current
              @check-change="handleCheckChange()"
              show-checkbox
              ref="tree"
            ></el-tree>
          </el-scrollbar>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCreate()" size="small">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 查看广播成员 -->
    <el-dialog
      title="查看广播成员"
      custom-class="inner-dialog"
      :close-on-click-modal="false"
      :modal="false"
      :visible.sync="dialogMemberList"
      :before-close="handleCloseMember"
      width="100%"
    >
      <div style="height:500px;">
        <div style="width:100%">
          <el-scrollbar wrap-style="overflow-x:hidden;height:200px">
            <el-table
              :data="memberData"
              ref="table"
              height="550"
              style="width: 100%"
              :highlight-current-row="true"
              cell-class-name="table-cell-custom"
              header-cell-class-name="table-herder-custom"
              size="small"
            >
              <el-table-column prop="realName" show-overflow-tooltip label="成员" align="center"></el-table-column>
              <el-table-column prop="myDutyName" show-overflow-tooltip label="职务" align="center"></el-table-column>
              <el-table-column prop="groupName" show-overflow-tooltip label="组" align="center"></el-table-column>
              <el-table-column prop="calledDevice" show-overflow-tooltip label="号码" align="center"></el-table-column>
            </el-table>
          </el-scrollbar>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogMemberList = false" size="small">返 回</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
const cityOptions = ['1', '2', '3', '4', '5', '6', '7']
import { mapGetters } from 'vuex'
import deepClone from '@/utils/clone'
import { getDuty, makeCall } from '@/api/data'
import { timingbroadcast, timingbroadcastget } from '@/api/dataManage'
export default {
  props: {
    timeBroadcastDialog: Boolean,
  },
  components: {},
  data() {
    return {
      currentTab: 'once',
      dialogAdd: false,
      form: {},
      tableData: [],
      dialogStatus: 'add',
      fileList: [],
      callStatus: {
        idle: { text: '空闲', pic: require('../../assets/images/idle.png') },
        broadcasting: {
          text: '广播中',
          pic: require('../../assets/images/Broadcast.png'),
        },
      },
      callMode: 'once',
      broadcastNum: 1,
      checkedCities: [],
      cities: cityOptions,
      dialogMemberList: false,
      memberData: [],
      showInputNum: true,
    }
  },
  computed: {
    ...mapGetters({
      userTreeData: 'userTreeData',
      telOperatorMap: 'telOperatorMap',
      telEmployeeMap: 'telEmployeeMap',
      groupMap: 'groupMap',
    }),
  },
  methods: {
    init() {
      this.handleGetDuty('once')
      this.currentTab = 'once'
    },
    eventMore(e) {
      let _this = this
      console.log(e)
      switch (e.type) {
        case 'TimingBroadcast':
          if (e.result == 'succ') {
            this.init()
          } else {
            this.$message.error('创建定时广播失败')
          }
          break
        default:
          break
      }
    },
    //关闭
    handleClose() {
      this.$emit('update:timeBroadcastDialog', false)
    },
    //获取列表
    handleGetDuty(type) {
      let _this = this
      timingbroadcast().then((res) => {
        let list = res.data.eventdata
        list = list.filter((e) => {
          return e.callMode == type
        })
        list.forEach((e) => {
          if (e.date) {
            let dateArr = e.date.split('|')
            e.beginDate = dateArr[0]
            e.endDate = dateArr[1]
            let playDay = ''
            dateArr.forEach((el, index) => {
              if (index != 0) {
                playDay = playDay + ','
              }
              playDay = playDay + el
            })
            e.playDay = playDay
          }
        })
        _this.tableData = list
      })
    },
    handleClick(tab, event) {
      this.handleGetDuty(tab.name)
      this.callMode = tab.name
    },
    //编辑
    handleModify(item) {
      this.form = { ...item }
      this.dialogAdd = true
      this.dialogStatus = 'update'
    },
    //打开新增
    handleAdd() {
      let _this = this
      this.dialogAdd = true
      this.form = { play: '1' }
      this.dialogStatus = 'add'
      this.handleGetBroadcastFile()
      this.$nextTick(() => {
        _this.$refs.tree.setCheckedKeys([])
      })
    },
    handleAddClose() {
      this.dialogAdd = false
    },
    //新增
    handleCreate() {
      let _this = this
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let date = ''
          if (this.callMode == 'once') {
            date = this.form.beginDate + '|' + this.form.endDate
          } else if (this.callMode == 'looping') {
            if (this.checkedCities.length == 0) {
              this.$message.error('请选择星期')
              return
            }
            this.checkedCities.forEach((e, index) => {
              if (index != 0) {
                date = date + '|'
              }
              date = date + e
            })
          }
          let called = []
          this.form.calledDevice.forEach((e) => {
            called.push({ calledDevice: e.key })
          })
          let fileName = ''
          let realFileName = ''
          this.fileList.forEach((e) => {
            if (e.fileid == this.form.broadcastFile) {
              fileName = e.filename
              realFileName = e.orifilename
            }
          })
          let obj = {
            request: {
              '@id': 'TimingBroadcast', //用以区分，在电话调度界面，不创建广播标签页
              '@type': 'TimingBroadcast',
              fileName: fileName,
              realFileName: realFileName,
              time: this.form.time,
              date: date,
              callMode: this.callMode,
              callLoop: this.form.play == 0 ? -1 : this.broadcastNum,
              called: called,
            },
          }
          makeCall(obj).then((res) => {
            if (res.status == 200) {
              this.dialogAdd = false
              this.init()
            }
          })
        }
      })
    },

    //删除
    handleDel() {
      let _this = this
      let delArr = this.$refs.myTable.store.states.selection
      if (delArr.length == 0) {
        this.$message.warning(this.$t('m.tip.DEL_EMPTY_TIP'))
        return
      }
      this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        delArr.forEach((element) => {
          timingbroadcastget(element.taskID).then((res) => {
            if (res.status == 200) {
              _this.dialogAdd = false
              _this.init()
            }
          })
        })
      })
    },
    //获取广播文件
    handleGetBroadcastFile() {
      SDK.voiceFileList().then((res) => {
        this.fileList = res.VoiceFileList
      })
    },
    //组织树选中成员
    handleCheckChange() {
      let checkedNodesAll = this.$refs.tree.getCheckedNodes()
      if (
        checkedNodesAll == null ||
        checkedNodesAll == undefined ||
        checkedNodesAll == ''
      ) {
        let form = this.form
        form.callTelNameArr = []
        form.calledDevice = []
        return
      }
      let plan = this.form
      plan.callTelNameArr = []
      plan.calledDevice = []
      const nodes = checkedNodesAll.filter(function (item) {
        return item.type == 'employee' || item.type == 'operator'
      })
      nodes.forEach((item) => {
        let obj = {
          // id: item.type == 'employee' ? item.obj.employeeID : item.obj.operatorID,
          key: item.type == 'employee' ? item.obj.defaultNo : item.obj.mainTel,
          value: item.label,
        }
        plan.callTelNameArr.push(item.label)
        plan.calledDevice.push(obj)
      })
      this.$forceUpdate()
    },
    //移除成员
    removeUserTag(val) {
      const calledDevice = this.form.calledDevice
      let call = calledDevice.filter((e) => {
        return e.value == val
      })
      this.form.calledDevice = calledDevice.filter((e) => {
        return e.value != val
      })
      if (call == undefined) {
        return
      }
      let id = ''
      let emp = this.telOperatorMap.get(call[0].key)
      if (emp) {
        id = emp.operatorID
      } else {
        emp = this.telEmployeeMap.get(call[0].key)
        id = emp.employeeID
      }
      this.$refs.tree.setChecked(id, false)
    },
    //  查看广播成员
    handleGetMemberList(row) {
      this.dialogMemberList = true
      let called = row.called
      called.forEach((e) => {
        const emp = this.telEmployeeMap.get(e.calledDevice)
        if (emp) {
          e.realName = emp.realName
          e.myDutyName = emp.dutyName.toString()
          e.groupName = this.getGroupNameById(emp.group[0].groupID)
        } else {
          const oper = this.telOperatorMap.get(e.calledDevice)
          if (oper) {
            e.realName = oper.realName
            e.myDutyName = '操作员'
            e.groupName = this.getGroupNameById(oper.groupID)
          }
        }
      })
      this.memberData = deepClone(called)
    },
    //获取组名
    getGroupNameById(id) {
      const group = this.groupMap.get(id)
      return group ? group.label : ''
    },
    //关闭查看广播成员
    handleCloseMember() {
      this.dialogMemberList = false
    },
    //单选框改变
    radioChange(val) {
      if (val == 0) {
        this.showInputNum = false
      } else {
        this.showInputNum = true
      }
    },
    //清空选中
    clearAll() {
      let form = this.form
      form.callTelNameArr = []
      form.calledDevice = []
      this.$refs.tree.setCheckedKeys([])
    },
  },
  mounted() {
    SDK.setEventMore(this.eventMore)
    this.init()
  },
}
</script>

<style lang="scss" scoped>
.el-dialog__wrapper {
  z-index: 2002 !important;
}
/deep/.timeBroadcast-dialog {
  cursor: default;
  width: 70%;
  background-color: #1a4969;
  .el-select--medium {
    vertical-align: bottom !important;
  }
  .el-dialog__header {
    padding-top: 10px;
    text-align: center;
    .el-dialog__title {
      color: #fff;
    }
    .el-dialog__close {
      color: #fff;
    }
  }
  .el-dialog__body {
    padding: 0 15px;
    .search-input {
      margin-bottom: 10px;
      .el-input__inner {
        background-color: #1a4969;
        color: #fff;
        width: 50%;
      }
    }
  }
  .el-dialog__footer {
    padding-bottom: 10px;
    .el-button {
      background-color: #1a4969;
      color: #fff;
      width: 70px;
    }
    .el-button:hover {
      background-color: #00b2ee;
    }
  }
  // 标签页
  .el-tabs__item {
    color: white !important;
  }
  .el-tabs__item:hover {
    color: #b7def9;
    cursor: pointer;
    background-color: #b7def9 !important;
  }
  .el-tabs__item.is-active {
    background-color: #6bb5e6 !important;
  }
  .el-tree {
    background-color: #172a47;
    color: #fff;
  }
  .default-scrollbar {
    width: 100%;
    height: calc(100% - 20px);
    background-color: #172a47;
  }

  /deep/.default-scrollbar__wrap {
    width: auto;
    overflow-x: hidden;
    margin-right: -20px !important;
  }

  /deep/.el-tree-node__content {
    height: 34px;
    cursor: default;

    &:hover {
      background-color: #172a47;
      border: 1px solid #d0cdcd;
      color: white;
    }
  }

  /deep/.el-tree-node.is-current > .el-tree-node__content {
    background-color: #6bb5e6;
    color: #000;
  }
  .el-table {
    td {
      border-bottom: 1px solid #2e67a8;
    }
    tr:hover > td {
      background-color: #2f6b8d;
    }
    background-color: #1a4969;
    .table-herder-custom {
      background-color: #2e67a8;
      color: #fff;
    }
    .table-cell-custom {
      background-color: #172a47;
      color: #fff;
      .el-link {
        color: #fff;
        margin-left: 20px;
        span {
          font-size: 10px;
        }
        &:hover {
          color: #06f7bb;
        }
      }
    }
    /deep/.el-table__body tr.current-row > td {
      background: #6bb5e6 !important;
    }
  }
  .el-dialog__wrapper {
    position: absolute;
    height: 100%;
    .inner-dialog {
      background-color: #1a4969;
      height: 100%;
      margin-top: 0 !important;
      margin-bottom: 0px;
      opacity: 0.96;
      .el-dialog__footer {
        position: absolute;
        bottom: 0px;
        right: 0px;
      }
      .back-to-list {
        color: #fff;
        height: 22px;
        width: 22px;
      }
      .el-form {
        .el-form-item__label {
          color: #fff;
        }
        .el-input__inner,
        .el-textarea__inner {
          background-color: #1a4969;
          color: #fff;
          // width: 40%;
        }
        .group-item {
          display: flex;
          flex-wrap: nowrap;
          align-items: center;
          .svg-icon {
            width: 19px;
            height: 19px;
            margin-right: 5px;
            cursor: pointer;
          }
          .add-label {
            color: #fff;
            cursor: pointer;
          }
          .el-input__inner {
            width: 240px;
          }
          &.add {
            margin-left: -1px;
            font-size: 13px;
            label {
              margin-left: 3px;
            }
            .valid-rule {
              color: #f56c6c;
              margin-left: 20px;
              font-size: 12px;
            }
          }
          .set-defaultNo {
            margin-left: 10px;
            font-style: oblique;
            .el-radio__label {
              font-size: 10px;
            }
          }
        }
      }
      .el-radio {
        color: white;
      }
      .el-checkbox {
        color: white;
      }
    }

    .trial-box {
      position: absolute;
      left: calc(50% - 100px);
      top: calc(50% - 50px);
      border: 1px solid rgba(255, 255, 255, 0.6);
      border-radius: 5px;
      width: 200px;
      height: 100px;
      display: flex;
      flex-flow: column;
      align-items: center;
      justify-content: center;
      .el-row {
        color: #fff;
      }
      .trial-loading {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        -webkit-animation: loading 1.1s infinite linear;
        animation: loading 1.2s infinite linear;
        @-webkit-keyframes loading {
          from {
            transform: rotate(0deg);
          }
          to {
            transform: rotate(360deg);
          }
        }
        @keyframes loading {
          from {
            transform: rotate(0deg);
          }
          to {
            transform: rotate(360deg);
          }
        }
      }
      .el-button {
        width: 70px;
        color: #fff;
        background-color: #1a4969;
        margin-top: 10px;
        &:hover {
          background-color: #00b2ee;
        }
      }
      .form-item-group {
        margin: 5px 0;
        .svg-button {
          height: 32px;
          display: flex;
          align-items: center;
          margin-bottom: 18px;
        }
      }
    }
  }
  .default-select-tree {
    right: 30px;
    position: absolute;
    bottom: 15%;
    height: 400px;
    width: 220px;
    background-color: #155175;
    border: 1px solid #fff;
    border-radius: 7px;
    z-index: 999999;
    .tree-scrollbar {
      border-radius: 7px;
      width: 100%;
      height: calc(100% - 40px);
      // background-color: #172a47;
      background-color: #155175;

      .el-tree {
        background-color: #155175 !important;
        color: #fff;
        /deep/.el-tree-node__content {
          height: 34px;
          cursor: default;
          background-color: #155175;
          &:hover {
            background-color: #616d70;
          }
        }
        /deep/.el-tree-node.is-current > .el-tree-node__content {
          background-color: #00b2ee !important;
          color: #ffffff;
        }
        .el-checkbox__input.is-checked {
          .el-checkbox__inner {
            background-color: green;
            border-color: green;
          }
        }
      }
    }
    /deep/.tree-scrollbar__wrap {
      width: auto;
      overflow-x: hidden;
      margin-right: -20px !important;
    }
    text-align: center;
    .el-button {
      width: 70px;
      background-color: #1a4969;
      color: #ffffff;
      &:hover {
        background-color: #409eff;
      }
    }
  }
}
</style>